﻿
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.IO;

namespace System.Security
{
    public class DES
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sInputString"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Encode(string sInputString, string sKey)
        {
            var data = Encoding.Default.GetBytes(sInputString);
            var DES = new DESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            var desencrypt = DES.CreateEncryptor();
            var result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            var desString = string.Empty;

            for (int i = 0; i < result.Length; i++)
                desString += result[i].ToString("x2");

            return desString;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sInputString"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decode(string sInputString, string sKey)
        {
            var data = new byte[sInputString.Length / 2];

            for (int i = 0; i < data.Length; i++)
                data[i] = byte.Parse(sInputString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);

            var DES = new DESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            ICryptoTransform desencrypt = DES.CreateDecryptor();

            return Encoding.Default.GetString(desencrypt.TransformFinalBlock(data, 0, data.Length));
        }
    }
}